import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '@/types'
import { authService } from '@/services/auth'
import router from '@/router'
import { ElMessage } from 'element-plus'

interface LoginForm {
  username: string
  password: string
}

interface RegisterForm {
  username: string
  password: string
  confirmPassword: string
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性：是否已认证
  const isAuthenticated = computed(() => !!user.value)

  function setToken(token: string) {
    localStorage.setItem('token', token)
  }

  function setUser(newUser: User) {
    user.value = newUser
  }

  async function register(form: RegisterForm) {
    loading.value = true
    error.value = null
    try {
      const response = await authService.register(form)
      user.value = response.user
      localStorage.setItem('token', response.token)
      ElMessage.success('注册成功')
    } catch (err: any) {
      error.value = err.message || '注册失败'
      ElMessage.error(error.value || '注册失败')
      throw err
    } finally {
      loading.value = false
    }
  }

  async function login(form: LoginForm) {
    loading.value = true
    error.value = null
    try {
      const response = await authService.login(form)
      user.value = response.user
      localStorage.setItem('token', response.token)
      ElMessage.success('登录成功')
    } catch (err: any) {
      error.value = err.message || '登录失败'
      ElMessage.error(error.value || '登录失败')
      throw err
    } finally {
      loading.value = false
    }
  }

  async function getCurrentUser() {
    try {
      loading.value = true
      error.value = null
      const currentUser = await authService.getCurrentUser()
      setUser(currentUser)
      return currentUser
    } catch (err: any) {
      error.value = err.message || '获取用户信息失败'
      user.value = null
      throw err
    } finally {
      loading.value = false
    }
  }

  function logout() {
    localStorage.removeItem('token')
    user.value = null
    ElMessage.success('已退出登录')
  }

  // 检查认证状态
  const checkAuth = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      user.value = null
      return
    }

    loading.value = true
    error.value = null
    try {
      const response = await authService.getCurrentUser()
      user.value = response
    } catch (err) {
      error.value = err instanceof Error ? err.message : '认证检查失败'
      user.value = null
      localStorage.removeItem('token')
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    user,
    loading,
    error,
    isAuthenticated,
    setToken,
    setUser,
    login,
    logout,
    getCurrentUser,
    register,
    checkAuth
  }
}) 